package com.jt.config;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedisLockConfig {
    /**
     *  redis 分布式锁
     */

    @Autowired
    private RedisTemplate redisTemplate;

    /*加锁*/
    public boolean setLock(String lockName, String uuid, long expireTime, TimeUnit milliseconds) {
        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(lockName, uuid, expireTime, TimeUnit.MILLISECONDS);
        return Boolean.TRUE.equals(aBoolean);
    }

    /*删除锁*/
    public boolean deleteLock(String lockKey, String uuid) {
        String uuidRes = (String) redisTemplate.opsForValue().get(lockKey);
        if (uuidRes.equals(uuid)) {
            return redisTemplate.delete("lockKey");
        }else {
            return false;
        }
    }
}
